package com.itbaizhan.openhis.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.itbaizhan.openhis.api.domain.User;
import com.itbaizhan.openhis.auth.AuthUtil;
import com.itbaizhan.openhis.domain.R;
import com.itbaizhan.openhis.form.LoginBody;
import com.itbaizhan.openhis.form.RegisterBody;
import com.itbaizhan.openhis.model.LoginUser;
import com.itbaizhan.openhis.service.SysLoginService;
import com.itbaizhan.openhis.service.TokenService;
import com.itbaizhan.openhis.utils.JwtUtils;
import com.itbaizhan.openhis.utils.SecurityUtils;
import com.itbaizhan.openhis.vo.AjaxResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * token 控制
 *
 * @author wcc
 */
@RestController
@RequestMapping("/login")
public class TokenController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 用户登录
     * @param form
     * @return
     */
    @PostMapping("/doLogin")
    public AjaxResult login(@RequestBody LoginBody form)
    {
        // 用户登录
        User userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return AjaxResult.success(tokenService.createToken(userInfo));
    }



    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (!StrUtil.isEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return AjaxResult.success();
    }


    /**
     * 刷新令牌
     * @param request
     * @return
     */
    @PostMapping("refresh")
    public AjaxResult refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (BeanUtil.isEmpty(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.success();
    }

    /**
     * 注册用户
     * @param registerBody
     * @return
     */
    @PostMapping("register")
    public AjaxResult register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
//        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return AjaxResult.success();
    }
}
